package com.estronger.shopmanage.ui.measure;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.estronger.shopmanage.R;
import com.estronger.shopmanage.base.BaseActivity;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.B15GetDetail;
import com.estronger.shopmanage.bean.B15GetDetail.Attchment;
import com.estronger.shopmanage.bean.B15GetDetail.Img;
import com.estronger.shopmanage.bean.B15GetDetail.MeasureItem;
import com.estronger.shopmanage.bean.B15GetDetail.MeasureItemimg;
import com.estronger.shopmanage.bean.B16PlanMeasure;
import com.estronger.shopmanage.bean.B16PlanMeasure.MeasureGoods;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.grab.activity.GrabPondActivity;
import com.estronger.shopmanage.ui.grab.bean.GrabOrderBean;
import com.estronger.shopmanage.ui.grab.presenter.GrabComPresenter;
import com.estronger.shopmanage.ui.grab.presenter.IGrabComView;
import com.estronger.shopmanage.utils.FileUtil;
import com.estronger.shopmanage.utils.TimeUtils;
import com.estronger.shopmanage.view.AppDialog;
import com.lidroid.xutils.http.RequestParams;
import com.soonfor.evaluate.tools.ComToast;
import com.soonfor.evaluate.tools.CustomDialog;
import com.soonfor.evaluate.tools.dialog.normal.NormalDialog;
import com.soonfor.evaluate.tools.dialog.normal.OnBtnClickL;

public class MeasureDetailActivity extends BaseActivity implements
		OnClickListener {

	private TextView tv_name, tv_phone, tv_time, tv_describle, tv_address,
			tv_actual_time, tv_actdemand, tv_finish_time, tv_conversation_time,
			tv_chazhi, tv_navname, tv_navmobile, tv_file_text1,tvFistCommand;

	private LinearLayout ll_condition_contener, ll_all_file_contener, llfPhone, llfGuide;
	private View rootView, compleshView, callView, smsView, navmobile_smsView;
	private String measureid, navNumber, navName;
	private ScrollView sv_root;
	private boolean isComplesh;
	private GrabOrderBean.DataBean goBean;//抢单对象
	private TextView tvfButton;
	NormalDialog ndialog;

	@Override
	protected void init() {
		isComplesh = getIntent().getBooleanExtra("isComplesh", false);
		measureid = getIntent().getStringExtra("measureid");
		try {
			goBean = (GrabOrderBean.DataBean) getIntent().getSerializableExtra("isGrabOrderBean");
		} catch (Exception e) {
			goBean = null;
		}
	}

	@Override
	protected void initView() {
		rootView = View.inflate(this, R.layout.activity_task_detail, null);
		setContentView(rootView);
		tvfButton = findViewById(R.id.tvfButton);
		if (goBean != null) {//抢单
			tvfButton.setVisibility(View.VISIBLE);
			tvfButton.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View view) {
					String hintText = "亲，抢单完成后请尽快与客户再次确认" + goBean.getTaskTypeDesc() + "日期，任务预期未处理，将会对您的信誉造成影响";
					ndialog = CustomDialog.getInstance().getNormalDialog(MeasureDetailActivity.this, "温馨提示", hintText,
							new OnBtnClickL() {
								@Override
								public void onBtnClick(View view) {
									ndialog.dismiss();
									showDialog("抢单中...", true);
									new GrabComPresenter(MeasureDetailActivity.this, new IGrabComView() {
										@Override
										public void refreshAfterGrabTask(boolean isSuccess, String msg) {
											if (isSuccess) {
												ComToast.showSuccessToast(MeasureDetailActivity.this, "抢单成功");
												GrabPondActivity.ItemPosition = 0;
												MeasureDetailActivity.this.finish();
											} else {
												ComToast.showFailToast(MeasureDetailActivity.this, "抢单失败");
											}
											dimssDialog();
										}
									}).grabTask(goBean.getFtaskid(), goBean.getFtasktype());
								}
							});
					ndialog.show();
				}
			});
		} else {
			tvfButton.setVisibility(View.GONE);
		}
		sv_root = (ScrollView) findViewById(R.id.detail_scroller);

		if (isComplesh) {
			RequestParams params = new RequestParams();
			params.addBodyParameter("sf_action", "getdetail");
			params.addBodyParameter("usercode", MyApplication.getUserCode());
			params.addBodyParameter("measureid", measureid);
			connect(params, NetManager.DETAIL);
			showDialog("获取测量详情中...", true);
		} else {
			RequestParams params = new RequestParams();
			params.addBodyParameter("sf_action", "getplanmeasure");
			params.addBodyParameter("usercode", MyApplication.getUserCode());
			params.addBodyParameter("measureid", measureid);
			connect(params, NetManager.DETAIL);
			showDialog("获取测量详情中...", true);
		}

	}

	private void initTitle(View root) {
		tv_name = (TextView) root.findViewById(R.id.order_item_name);
		tv_phone = (TextView) root.findViewById(R.id.order_item_phone);
		tv_time = (TextView) root.findViewById(R.id.order_item_appointment);
		tv_chazhi = (TextView) root.findViewById(R.id.order_item_appointment_time);
		tv_describle = (TextView) root.findViewById(R.id.order_item_describle);
		tv_address = (TextView) root.findViewById(R.id.order_item_location);
		tv_navname = (TextView) root.findViewById(R.id.navname);
		tv_navmobile = (TextView) root.findViewById(R.id.navmobile);
		ll_condition_contener = (LinearLayout) root.findViewById(R.id.goods_condition_contener);
		llfPhone = root.findViewById(R.id.llfPhone);
		llfGuide = root.findViewById(R.id.llfGuide);
		if (goBean != null) {
			llfPhone.setVisibility(View.GONE);
			llfGuide.setVisibility(View.GONE);
		} else {
			llfPhone.setVisibility(View.VISIBLE);
			llfGuide.setVisibility(View.GONE);
		}
		callView = root.findViewById(R.id.order_phone_call);
		smsView = root.findViewById(R.id.order_send_sms);
		navmobile_smsView = root.findViewById(R.id.navmobile_send_sms);

		tv_navmobile.setOnClickListener(this);
		navmobile_smsView.setOnClickListener(this);
		callView.setOnClickListener(this);
		smsView.setOnClickListener(this);
	}

	private Dialog dialog;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.navmobile_send_sms:
				if (isRightNumber(navNumber)) {
					Uri uri = Uri.parse("smsto:" + navNumber);
					Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
					startActivity(intent);
				}
				break;
			case R.id.order_send_sms:
				String number = tv_phone.getText().toString();
				if (isRightNumber(number)) {
					Uri uri = Uri.parse("smsto:" + number);
					Intent intent = new Intent(Intent.ACTION_SENDTO, uri);
					startActivity(intent);
				}
				break;
			case R.id.order_phone_call:
				String number2 = tv_phone.getText().toString();
				if (isRightNumber(number2)) {
					dialog = AppDialog.createDialog(this, tv_name.getText()
							.toString(), number2, this, measureid);
					dialog.show();
				}
				break;
			case R.id.navmobile:
				if (isRightNumber(navNumber)) {
					dialog = AppDialog.createDialog(this, this.navName, navNumber,
							this, measureid);
					dialog.show();
				}
				break;
			case R.id.ok:
				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
						+ navNumber));
				if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
					// TODO: Consider calling
					//    ActivityCompat#requestPermissions
					// here to request the missing permissions, and then overriding
					//   public void onRequestPermissionsResult(int requestCode, String[] permissions,
					//                                          int[] grantResults)
					// to handle the case where the user grants the permission. See the documentation
					// for ActivityCompat#requestPermissions for more details.
					return;
				}
				startActivity(intent);
				dialog.dismiss();
				break;
		}
	}

	/**
	 * 当前activity请求网络成功的回调
	 *
	 * @params code 各个接口返回的唯一识别码，用来判断是哪个接口成功返回
	 * @params result 网络请求成功返回的数据
	 */
	@Override
	protected void onNetSuccess(int code, String result) {
		// Log.i("result", "DETAIL = " + result);
		if (NetManager.DETAIL == code) {
			if (isComplesh) { // 已经测量完成的内容
				compleshView = View.inflate(this, R.layout.order_detail, null);
				sv_root.addView(compleshView);
				showCompleshView(result);
			} else {
				sv_root.removeAllViews();
				View childNoComplesh = View.inflate(this,
						R.layout.measure_item_include, null);
				sv_root.addView(childNoComplesh);
				initTitle(sv_root);
				showNocompleshView(result);
			}
		}
		super.onNetSuccess(code, result);
	}

	// 完成测量时展示的信息
	public void showCompleshView(String result) {
		compleshView.setVisibility(View.VISIBLE);
		B15GetDetail detail = gson.fromJson(result, B15GetDetail.class);
		if (detail.success && detail.data != null) {
			initConpleshView();
			if (TextUtils.isEmpty(detail.data.buildname)) {
				tv_name.setText(detail.data.cstname);
			} else {
				tv_name.setText(detail.data.buildname + "-"
						+ detail.data.cstname);
			}
			tv_actual_time.setText(detail.data.actmeasuredate);
			tv_finish_time.setText(detail.data.predesignenddate);
			tv_conversation_time.setText(detail.data.prjcontactdate);
			tv_actdemand.setText(detail.data.actdemand);
			tvFistCommand.setText(detail.data.firstdemand.trim());
			// 这里做每个货物的展示
			for (int i = 0; i < detail.data.measureitem.size(); i++) {
				MeasureItem data = detail.data.measureitem.get(i);
				View v = View.inflate(this, R.layout.order_detail_item, null);
				goods_name = (TextView) v.findViewById(R.id.goods_name);
				goods_count = (TextView) v.findViewById(R.id.goods_count);
				goods_property = (TextView) v.findViewById(R.id.goods_property);
				goods_img = (ImageView) v.findViewById(R.id.goods_item_img);
				goods_feature = (TextView) v.findViewById(R.id.goods_feature);

				goods_name.setText(data.goodsname);
				goods_property.setText(data.sizedesc);
				goods_count.setText(data.qty);
				goods_feature.setText(data.unitname);
				MyApplication.imageLoader.displayImage(
						NetManager.getDownloadURL() + "?filepath="
								+ data.simplepicfile, goods_img,
						MyApplication.options);

				LinearLayout item_bill_contener, item_place_contener;
				item_bill_contener = (LinearLayout) v
						.findViewById(R.id.detail_item_img_contener);
				item_place_contener = (LinearLayout) v
						.findViewById(R.id.detail_item_img_contener2);

				for (int a = 0; a < data.measureitemimg.size(); a++) {
					MeasureItemimg img = data.measureitemimg.get(a);
					if (!TextUtils.isEmpty(img.path)) {
						RelativeLayout rl = (RelativeLayout) View.inflate(this,
								R.layout.img, null);
						ImageView iv = (ImageView) rl.getChildAt(0);
						MyApplication.imageLoader.displayImage(
								NetManager.getDownloadURL() + "?filepath="
										+ img.path, iv, MyApplication.options);
						iv.setTag(NetManager.getDownloadURL() + "?filepath="
								+ img.path);

						if (img.type == 1) {
							item_bill_contener.addView(rl);
							MyApplication.imageLoader.displayImage(
									NetManager.getDownloadURL() + "?filepath="
											+ img.path, iv,
									MyApplication.options);
						} else if (img.type == 2) {
							item_place_contener.addView(rl);
							MyApplication.imageLoader.displayImage(
									NetManager.getDownloadURL() + "?filepath="
											+ img.path, iv,
									MyApplication.options);
						} else if (img.type == 3) {

							View v1 = View.inflate(this, R.layout.file_item,
									null);
							TextView file_text1 = (TextView) v1
									.findViewById(R.id.detail_file_text1);
							file_text1.setText(FileUtil.getFileName2(img.path));
							LinearLayout item_file_contener = (LinearLayout) v
									.findViewById(R.id.item_all_file_contener);
							item_file_contener.addView(v1);

						}
					}
				}
				goods_contener.addView(v);
			}

			// 下面的处理都是做整体的那一部分展示
			if (detail.data.imgitem.size() > 0) {
				for (int i = 0; i < detail.data.imgitem.size(); i++) {
					Img img = detail.data.imgitem.get(i);
					if (!TextUtils.isEmpty(img.imgpath)) {
						RelativeLayout rl = (RelativeLayout) View.inflate(this,
								R.layout.img, null);
						ImageView iv = (ImageView) rl.getChildAt(0);
						MyApplication.imageLoader.displayImage(
								NetManager.getDownloadURL() + "?filepath="
										+ img.imgpath, iv,
								MyApplication.options);
						iv.setTag(NetManager.getDownloadURL() + "?filepath="
								+ img.imgpath);
						if (img.type == 1) {
							all_bill_contener.addView(rl);
						} else {
							all_place_contener.addView(rl);
						}
					}
				}
				if (all_bill_contener.getChildCount() > 0) {
					((View) (all_bill_contener.getParent()))
							.setVisibility(View.VISIBLE);
				}
				if (all_place_contener.getChildCount() > 0) {
					((View) (all_place_contener.getParent()))
							.setVisibility(View.VISIBLE);
				}

				// 显示整体的文件数据
				if (detail.data.attachment != null) {

					Attchment att;
					for (int i = 0; i < detail.data.attachment.size(); i++) {
						att = detail.data.attachment.get(i);
						View v = View.inflate(this, R.layout.file_item, null);
						tv_file_text1 = (TextView) v
								.findViewById(R.id.detail_file_text1);

						tv_file_text1.setText(att.title);
						ll_all_file_contener.addView(v);
					}
				}
			} else {
				// detail_all_contener.setVisibility(View.GONE);
			}
		}
	}

	// 还没有完成测量时展示的信息
	public void showNocompleshView(String result) {

		B16PlanMeasure detail = gson.fromJson(result, B16PlanMeasure.class);
		if (TextUtils.isEmpty(detail.data.buildname)) {
			tv_name.setText(detail.data.cstname);
		} else {
			tv_name.setText(detail.data.buildname + "-" + detail.data.cstname);
		}

		tv_phone.setText(detail.data.cstmobile);
		tv_time.setText(detail.data.planmeasuredate);
		tv_chazhi.setText(TimeUtils.chaZhi(detail.data.planmeasuredate));
		tv_describle.setVisibility(detail.data.firstdemand!= null && detail.data.firstdemand.length() > 0?View.VISIBLE:View.GONE);
		tv_describle.setText("初步需求:" + detail.data.firstdemand);
		tv_address.setText(detail.data.address);
		tv_navname.setText("导购员: " + detail.data.navname);
		tv_navmobile.setText(detail.data.navmobile);
		navName = detail.data.navname;
		navNumber = detail.data.navmobile;
		// 测量货物的详细信息
		for (int i = 0; i < detail.data.measureitem.size(); i++) {
			MeasureGoods data = detail.data.measureitem.get(i);
			View v = View.inflate(this, R.layout.goods_condition, null);
			goods_name = (TextView) v.findViewById(R.id.goods_name);
			goods_count = (TextView) v.findViewById(R.id.goods_count);
			goods_property = (TextView) v.findViewById(R.id.goods_property);
			goods_img = (ImageView) v.findViewById(R.id.goods_item_img);
			goods_feature = (TextView) v.findViewById(R.id.goods_feature);
			condition_text = (TextView) v.findViewById(R.id.condition_text);
			condition_text.setText("测量条件");

			goods_name.setText(data.goodsname);
			goods_property.setText(data.sizedesc);
			goods_count.setText(data.qty);
			goods_feature.setText(data.unitname);
			MyApplication.imageLoader.displayImage(NetManager.getDownloadURL()
							+ "?filepath=" + data.simplepicfile, goods_img,
					MyApplication.options);
			LinearLayout condition_group = (LinearLayout) v
					.findViewById(R.id.item_conditions);
			for (int j = 0; j < data.conditionitem.size() && j < 10; j++) {
				View item = View.inflate(this, R.layout.condition_item, null);
				// TextView pos_tv = (TextView)
				// item.findViewById(R.id.condition_position);
				TextView content = (TextView) item
						.findViewById(R.id.condition_content);
				CheckBox cb = (CheckBox) item.findViewById(R.id.condition_cb);

				// pos_tv.setText(pos[j]);
				content.setText(data.conditionitem.get(j).content);
				if ("1".equals(data.conditionitem.get(j).ifcheck)) {
					cb.setChecked(true);
				}
				cb.setClickable(false);
				condition_group.addView(item);
			}

			ll_condition_contener.addView(v);
		}
	}

	private String[] pos = { "①", "②", "③", "④", "⑤", "⑥", "⑦", "⑧", "⑨", "⑩" };
	private TextView goods_name, goods_count, goods_property, goods_feature,
			condition_text;
	private ImageView goods_img;
	private LinearLayout detail_all_contener, all_bill_contener,
			all_place_contener, goods_contener;

	// condition_group,
	private void initConpleshView() {
		tv_name = (TextView) findViewById(R.id.measure_result_name_real);
		tv_actual_time = (TextView) findViewById(R.id.result_time_real);
		tv_finish_time = (TextView) findViewById(R.id.detail_finish_date);
		tv_conversation_time = (TextView) findViewById(R.id.detail_conversation_time);
		tv_actdemand = (TextView) findViewById(R.id.need_remark);
		tvFistCommand = (TextView) findViewById(R.id.firstneed_remark);
		goods_contener = (LinearLayout) findViewById(R.id.measure_complesh_contener);

		detail_all_contener = (LinearLayout) findViewById(R.id.measure_detail_all_contener);
		all_bill_contener = (LinearLayout) findViewById(R.id.detail_all_bill_contener);
		all_place_contener = (LinearLayout) findViewById(R.id.detail_all_place_contener);

		ll_all_file_contener = (LinearLayout) findViewById(R.id.detail_all_file_contener);
		// file_text1 = (TextView) findViewById(R.id.detail_file_text1);
		// file_text2 = (TextView) findViewById(R.id.detail_file_text2);
	}

	// 是否显示货物的测量条件
	public void showCondition(View view) {
		ImageView rb = (ImageView) view;
		View condition_group = ((View) view.getParent().getParent())
				.findViewById(R.id.item_conditions);
		if (condition_group.getVisibility() == View.VISIBLE) {
			rb.setBackgroundResource(R.drawable.hide_view_down);
			condition_group.setVisibility(View.GONE);
		} else {
			rb.setBackgroundResource(R.drawable.hide_view_up);
			valueAnim(0, condition_group.getMeasuredHeight(), condition_group);
			condition_group.setVisibility(View.VISIBLE);
		}
	}

	// 看大图
	public void viewPhoto(View view) {
		viewGoods(view);
	}

	public void viewGoods(View view) {
		showGoodsPop(view.getTag().toString());
	}

	private PopupWindow sharedPop;

	// 看大图
	public void showGoodsPop(String url) {

		if (sharedPop == null) {
			View contentView = View.inflate(this, R.layout.shared_pop_window,
					null);
			sharedPop = new PopupWindow(contentView, LayoutParams.MATCH_PARENT,
					LayoutParams.MATCH_PARENT, true);
			sharedPop.setAnimationStyle(R.style.goods_pop);
			sharedPop.setBackgroundDrawable(new BitmapDrawable());
			sharedPop.setFocusable(true);
		}
		ImageView iv = (ImageView) sharedPop.getContentView().findViewById(
				R.id.goods_img_big);
		iv.setImageResource(R.drawable.goods_default);
		// iv.setImageBitmap(BitmapFactory.decodeFile(url));
		MyApplication.imageLoader.displayImage(url, iv, MyApplication.options);
		sharedPop.showAtLocation(rootView, Gravity.CENTER, 0, 0);
	}

	@Override
	public void onBackPressed() {
		if (null != sharedPop && sharedPop.isShowing()) {
			sharedPop.dismiss();
		} else {
			super.onBackPressed();
		}
	}

	@Override
	protected void onDestroy() {
		if (sharedPop != null && sharedPop.isShowing()) {
			sharedPop.dismiss();
		}
		super.onDestroy();
	}

	public void closeGoodsPop(View view) {
		sharedPop.dismiss();
	}

}
